package com.rt.cloud.auth.controller.captchaSlide;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.utils.others.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.InputStream;
import java.util.*;


/**
 * 验证码控制器
 * @author wxy
 */
@Component
@RestController
@RequestMapping("/oauth/slide")
public class VerifyImageController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String IMG_PATH = "/image/pc/picture/*.*";
    private static final String TEMP_IMG_PATH = "/image/pc/temp/temp.png";
    private static final Long IMG_CACHE_EX_TIME = 120L;

    /**
     * 获取验证码
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getImageVerifyCode")
    public Result getImageVerifyCode() throws Exception {
        // 清理过期 slide verify uuid 数据
        Result resultDel = restTemplate.getForObject("http://scm-epcodeless-core/core/coding/tmptUserSetting/deletePhysicalBatch4slideVerify?minute=10", Result.class);
        // System.out.println("清理过期 slide verify uuid 数据:"+resultDel);
        // 读取图库目录
        List<File> imgList = queryFileList(IMG_PATH);
        int randNum = new Random().nextInt(imgList.size());
        File targetFile = imgList.get(randNum);
        List<File> tempimgList = queryFileList(TEMP_IMG_PATH);
        File tempImgFile = tempimgList.get(0);
        // 根据模板裁剪图片
        Map<String, Object> resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile, targetFile);
        int xWidth = (int) resultMap.get("xWidth");
        // sessionId 为key，value滑动距离X轴，缓存120秒
        String slideUuid = "slide-verify-uuid-"+IdWorker.get32UUID();
        // save to db
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", slideUuid);
        jsonObject.put("value", xWidth);
        String content = jsonObject.toJSONString();
        HttpEntity<String> request = new HttpEntity<>(content, headers);
        String url = "http://scm-epcodeless-core/core/coding/tmptUserSetting/createOrUpdate4GlobalUnique";
        Result result  = restTemplate.postForObject(url, request, Result.class);
        if (!result.isSuccess()) {
            return Result.builder().fault("加载滑动验证模块失败");
        }

        // 移除map的滑动距离，不返回给前端
        resultMap.remove("xWidth");
        resultMap.put("slideUuid", slideUuid);

        //Thread.sleep(0);

        return Result.builder(resultMap);
    }

    @PostMapping(value = "/checkCaptchaImg")
    public Result checkCaptchaImg(String distance, String slideUuid) {
        // 校验滑块随机数
        if (StringUtils.isNull(distance)||StringUtils.isNull(slideUuid)) {
            return Result.builder().fault("请使用滑块验证码");
        }

        String url = "http://scm-epcodeless-core/core/coding/tmptUserSetting/myPage4GlobalUniqueByName?name="+slideUuid;
        Result result = restTemplate.getForObject(url, Result.class);
        if (!result.isSuccess()) {
            return Result.builder().fault("滑动验证模块:uuid读取失败");
        }
        String distanceDb = result.getRemark();
        if (StringUtils.isNull(distanceDb)) {
            return Result.builder().fault("滑动验证失败");
        }
        int distanceInt = Integer.parseInt(distance);
        int distanceDbInt = Integer.parseInt(distanceDb);
        if (Math.abs(distanceInt - distanceDbInt) > 10) {
            //验证不通过
            return Result.builder().fault("请拖动到正确的位置");
        }

        //验证通过
        return Result.builder();
    }

    /**
     * 获取图片，由于spring boot打包成jar之后，获取到获取不到resources里头的图片，对此进行处理
     * @param path
     * @return
     * @author pangxianhe
     * @date 2020年1月2日
     */
    public List<File> queryFileList(String path) {
        //获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<File> filelist = new ArrayList<File>();
        // 获取远程服务器IP和端口
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources(path);

            for(Resource resource : resources) {
                //获得文件流，因为在jar文件中，不能直接通过文件资源路径拿到文件，但是可以在jar包中拿到文件流
                InputStream stream = resource.getInputStream();
                String targetFilePath =resource.getFilename();
                File ttfFile = new File("slideImage/pc/"+targetFilePath);
                /*if(!ttfFile.getParentFile().exists()) {
                	ttfFile.getParentFile().mkdir();
                }*/
                FileUtils.copyInputStreamToFile(stream, ttfFile);
                filelist.add(ttfFile);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return filelist;
    }

}
